//
//  KLReceiveKeyTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/8/10.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLReceiveKeyTableViewController.h"
#import "KLHelp.h"
#import "KLHttpAPI.h"
#import "HemaConst.h"
#import "HemaFunction.h"
#import "Masonry.h"
#import "JRToast.h"
#import <objc/runtime.h>
#import "KLTranspondKeysVC.h"

static NSString *AssociatedKeyButton3 = @"Button3IndexPath";

@interface KLReceiveKeyTableViewController ()<UIAlertViewDelegate>
{
    NSMutableArray *selectedArr;//二级列表是否展开状态
}
@property (nonatomic,strong) NSMutableArray *r_key_list_arr; //所有钥匙的原始列表
@property (nonatomic,strong) NSMutableArray *r_receivedKeys; //所有收到的钥匙列表
@property (nonatomic,strong) NSMutableArray *r_keysNamesArr;//可打开锁的名字数组
@property (nonatomic,strong) NSMutableArray *r_keysOrderOKArr;//排序完成后的数组

@property (nonatomic,strong) NSDictionary *r_clickKeyDic;//点击的钥匙字典
@end

@implementation KLReceiveKeyTableViewController
-(NSMutableArray *)r_receivedKeys{
    if(!_r_receivedKeys){
        _r_receivedKeys = [NSMutableArray array];
    }
    return _r_receivedKeys;
}

-(NSMutableArray *)r_keysNamesArr{
    if(!_r_keysNamesArr){
        _r_keysNamesArr = [NSMutableArray array];
    }
    return _r_keysNamesArr;
}

-(void)viewWillAppear:(BOOL)animated{
    //刷新列表
    [self refreshReceiveKeyList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化导航栏
    [self naveSet];
    self.tableView.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    selectedArr = [[NSMutableArray alloc] init];
}

#pragma mark - tableview的代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.r_keysNamesArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *string = [NSString stringWithFormat:@"%ld",(long)section];
    if ([selectedArr containsObject:string]) {
        UIImageView *imageV = (UIImageView *)[self.tableView viewWithTag:20000+section];
        imageV.image = [UIImage imageNamed:@"buddy_header_arrow_down@2x.png"];
        NSMutableArray *arr = self.r_keysOrderOKArr[section];
        return arr.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"receiveKeyList"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"receiveKeyList"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    
    //当前是第几个表头
    NSString *indexStr = [NSString stringWithFormat:@"%ld",(long)indexPath.section];
    if (![selectedArr containsObject:indexStr]) {
        return cell;
    }
    
    NSDictionary *lockDic = self.r_keysOrderOKArr[indexPath.section][indexPath.row];
    NSString *valid_type = [lockDic objectForKey:@"valid_type"];
    if(valid_type.integerValue == 1){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"未生效";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(238, 230, 133);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }else if(valid_type.integerValue == 2){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"已过期";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(240, 101, 101);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }else if (valid_type.integerValue == 4){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"可使用";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(0, 205, 102);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }else if (valid_type.integerValue == 3){
        UILabel *notice = [[UILabel alloc]init];
        notice.text = @"永久有效";
        notice.numberOfLines = 0;
        notice.font = [UIFont systemFontOfSize:14];
        notice.textAlignment = NSTextAlignmentCenter;
        notice.textColor = RGB_UI_COLOR(0, 205, 102);
        [cell.contentView addSubview:notice];
        [notice mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(cell.contentView).with.offset(0);
            make.width.mas_equalTo(17);
        }];
    }
    
    UILabel *lockMasterName = [[UILabel alloc]init];
//    if([[lockDic objectForKey:@"type"] isEqualToString:@"1"]){
//        lockMasterName.text = @"平等钥匙";
//    }else if([[lockDic objectForKey:@"type"] isEqualToString:@"2"]){
//        lockMasterName.text = @"临时钥匙";
//    }
    [cell.contentView addSubview:lockMasterName];
    [lockMasterName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell).with.offset(5);
        make.height.mas_equalTo(25);
        make.left.equalTo(cell).with.offset(45);
    }];
    
    UILabel *nameLabel = [[UILabel alloc]init];
    nameLabel.text = [lockDic objectForKey:@"name"];
    nameLabel.textAlignment = NSTextAlignmentRight;
    nameLabel.textColor = [UIColor lightGrayColor];
    nameLabel.alpha = 0.8;
    nameLabel.font = [UIFont systemFontOfSize:15];
    nameLabel.numberOfLines = 1;
    nameLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    [cell.contentView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lockMasterName).with.offset(0);
        make.right.equalTo(cell).with.offset(-40);
        make.left.equalTo(lockMasterName).with.offset(80);
    }];
    
    //编辑钥匙别名按钮
    UIButton *editNameBtn = [[UIButton alloc]init];
    [editNameBtn setBackgroundImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
    [editNameBtn addTarget:self action:@selector(r_eidtKeyName:) forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(editNameBtn, &AssociatedKeyButton3, indexPath, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [cell.contentView addSubview:editNameBtn];
    [editNameBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(nameLabel).with.offset(0);
        make.right.equalTo(nameLabel).with.offset(25);
        make.height.mas_equalTo(20);
        make.width.mas_equalTo(20);
    }];
    
    UILabel *timeLabel = [[UILabel alloc]init];
    timeLabel.textColor = [UIColor lightGrayColor];
    timeLabel.alpha = 0.8;
    timeLabel.font = [UIFont systemFontOfSize:13];
    NSString *starTime = [lockDic objectForKey:@"startdate"];
    starTime = [starTime substringToIndex:16];
    NSString *endTime = [lockDic objectForKey:@"enddate"];
    endTime = [endTime substringToIndex:16];
    timeLabel.text = [NSString stringWithFormat:@"有效期:%@至%@",starTime,endTime];
    
    [cell.contentView addSubview:timeLabel];
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell).with.offset(30);
        make.height.mas_equalTo(25);
        make.left.equalTo(cell).with.offset(45);
    }];
    
    UILabel *phoneLabel = [[UILabel alloc]init];
    phoneLabel.textColor = [UIColor lightGrayColor];
    phoneLabel.alpha = 0.8;
    phoneLabel.font = [UIFont systemFontOfSize:13];
    phoneLabel.text = [NSString stringWithFormat:@"来自用户:%@ （%@）",[lockDic objectForKey:@"send_phone"],[lockDic objectForKey:@"send_username"]];
    [cell.contentView addSubview:phoneLabel];
    [phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell).with.offset(50);
        make.height.mas_equalTo(25);
        make.left.equalTo(cell).with.offset(45);
    }];
    
    UILabel *address = [[UILabel alloc]init];
    address.textColor = [UIColor lightGrayColor];
    address.numberOfLines = 1;
    address.lineBreakMode = NSLineBreakByTruncatingMiddle;
    address.alpha = 0.8;
    address.font = [UIFont systemFontOfSize:13];
    address.text = [NSString stringWithFormat:@"地址:%@",[lockDic objectForKey:@"address"]];
    [cell.contentView addSubview:address];
    if([[lockDic objectForKey:@"type"] isEqualToString:@"0"]){
        [address mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell).with.offset(50);
            make.height.mas_equalTo(25);
            make.left.equalTo(cell).with.offset(45);
            make.right.equalTo(cell).with.offset(-15);
        }];
    }else{
        [address mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell).with.offset(70);
            make.height.mas_equalTo(25);
            make.left.equalTo(cell).with.offset(45);
            make.right.equalTo(cell).with.offset(-15);
        }];
    }
    
    NSArray *sectionKeys = self.r_keysOrderOKArr[indexPath.section];
    if (indexPath.row != sectionKeys.count-1){
        UIImageView *imageLine = [[UIImageView alloc]initWithFrame:CGRectMake(40, 94, UI_View_Width-45, 1.5)];
        imageLine.image = [UIImage imageNamed:@"line.png"];
        [cell.contentView addSubview:imageLine];
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    NSDictionary *keyDic = self.r_keysOrderOKArr[indexPath.section][indexPath.row];
    NSString *keyType = [keyDic objectForKey:@"keyright"];
    UITableViewRowAction *action0 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"转发" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        // 收回左滑出现的按钮(退出编辑模式)
        tableView.editing = NO;
        if(keyType.integerValue == 1){
            KLTranspondKeysVC *transpondKeysVC = [[KLTranspondKeysVC alloc]init];
            transpondKeysVC.keyDetailDic = [self.r_keysOrderOKArr[indexPath.section][indexPath.row] copy];
            [self.navigationController pushViewController:transpondKeysVC animated:YES];
        }else if (keyType.integerValue == 0){
            [KLHelp showTextHUDforView:self.view text:@"该钥匙为不可转发钥匙"];
        }
    }];
    if(keyType.integerValue == 1){
        action0.backgroundColor = [UIColor greenColor];
    }else if (keyType.integerValue == 0){
        action0.backgroundColor = [UIColor grayColor];
    }
    
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"删除%zd",indexPath.row);
        tableView.editing = NO;
        NSDictionary *keyDic = self.r_keysOrderOKArr[indexPath.section][indexPath.row];
        NSLog(@"key_id:%@",[keyDic objectForKey:@"id"]);
        [KLHttpAPI removeOutOfDateChildKeyWithToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] key_id:[keyDic objectForKey:@"id"] completionHandler:^(MKNetworkOperation *operation) {
            NSDictionary *backDic = [operation responseJSON];
            NSString *issuccess = [backDic objectForKey:@"success"];
            if(issuccess.integerValue == 1){
                [self refreshReceiveKeyList];
            }else{
                [JRToast showWithText:[backDic objectForKey:@"msg"]];
            }
        } errorHandler:^(NSString *error) {
        }];
    }];
    action1.backgroundColor = [UIColor redColor];
    return @[action0,action1];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *vw = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 40)];
    vw.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, UI_View_Width, 40)];
    NSDictionary *lockMaster = self.r_keysOrderOKArr[section][0];
    label.text = [NSString stringWithFormat:@"%@ (%@)",self.r_keysNamesArr[section],[lockMaster objectForKey:@"name"]];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = RGB_UI_COLOR(132, 112, 255);
    label.font = [UIFont systemFontOfSize:15];
    label.alpha = 0.75;
    [vw addSubview:label];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 10, 20, 20)];
    imageView.tag = 20000+section;
    
    //判断是不是选中状态
    NSString *string = [NSString stringWithFormat:@"%ld",(long)section];
    if ([selectedArr containsObject:string]) {
        imageView.image = [UIImage imageNamed:@"buddy_header_arrow_down@2x.png"];
    }
    else{
        imageView.image = [UIImage imageNamed:@"buddy_header_arrow_right@2x.png"];
    }
    [vw addSubview:imageView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, UI_View_Width, 40);
    button.tag = 100+section;
    [button addTarget:self action:@selector(doButton_r:) forControlEvents:UIControlEventTouchUpInside];
    [vw addSubview:button];
    
    UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 39, UI_View_Width, 1.5)];
    lineImage.image = [UIImage imageNamed:@"line.png"];
    [vw addSubview:lineImage];
    
    return vw;
}-(void)doButton_r:(UIButton *)sender{
    NSString *string = [NSString stringWithFormat:@"%zd",sender.tag-100];
    //数组selectedArr里面存的数据和表头想对应，方便以后做比较
    if([selectedArr containsObject:string]){
        [selectedArr removeObject:string];
    }else{
        [selectedArr addObject:string];
    }
    
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:sender.tag-100];
    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40.0f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 95;
}

#pragma mark - 从服务器获取钥匙列表
-(void)refreshReceiveKeyList{
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI requestKeyListWith:token completionHandler:^(NSDictionary *responseDic) {
        NSString *isSuccess = [responseDic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            NSDictionary *infor = [responseDic objectForKey:@"infor"];
            NSArray *listItems = [infor objectForKey:@"listItems"];
            if(![[infor objectForKey:@"totalCount"] isEqualToString:@"0"] && ![[infor objectForKey:@"listItems"] isKindOfClass:[NSNull class]]){
                self.r_key_list_arr = [NSMutableArray arrayWithArray:listItems];
                //拿到钥匙列表后存入底层
                NSMutableArray *masterKeysArr = [NSMutableArray array];
                NSMutableArray *childKeysArr = [NSMutableArray array];
                //目前存的只有锁主钥匙,之后要做判断，并分开存储锁主钥匙和子钥匙
                for (NSDictionary *keyDic in self.r_key_list_arr) {
                    NSString *valid_type = [keyDic objectForKey:@"valid_type"];
                    if(valid_type.integerValue == 1 || valid_type.integerValue == 2){
                        continue;
                    }
                    
                    NSString *type = [keyDic objectForKey:@"keyright"];
                    if(type.integerValue == 3){//0是不可转发钥匙，1是可转发钥匙，2是二级锁主钥匙，3是锁主钥匙
                        [masterKeysArr addObject:keyDic];
                    }else{
//                        NSString *parentFlag = [keyDic objectForKey:@"parentflag"];//2是发出的钥匙，3是收到的钥匙
//                        if(parentFlag.integerValue == 3){
                            [childKeysArr addObject:keyDic];
//                        }
                    }
                }
                if(childKeysArr.count == 0){
                    [KLHelp setNoDateImageWithView:self.view type:0];
                }
                
                [[NSUserDefaults standardUserDefaults] setObject:masterKeysArr forKey:MASTER_KEY_ARRAY];
                [[NSUserDefaults standardUserDefaults] setObject:childKeysArr forKey:SUBMIT_KEY_ARRAY];
                //对钥匙进行分组
                [self groupingKeys];
                [self.tableView reloadData];
            }else{
                [JRToast showWithText:[responseDic objectForKey:@"msg"]];
            }
        }
        //隐藏进度条
        [KLHelp hideAllHUDsForView:self.tableView animated:YES];
        
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [KLHelp setNoDateImageWithView:self.view type:1];
    }];
}

#pragma mark - 对钥匙进行分组
-(void)groupingKeys{
    [self.r_keysNamesArr removeAllObjects];
    [self.r_receivedKeys removeAllObjects];
    //取出所有收到的钥匙
    for (NSDictionary *keyDic in self.r_key_list_arr) {
        if([[keyDic objectForKey:@"parentflag"] isEqualToString:@"2"]){
            [self.r_receivedKeys addObject:keyDic];
        }
    }
    NSLog(@"收到的钥匙是:%@",self.r_receivedKeys);
    
    //获得所有不同的锁编码
    for (NSDictionary *keyDic in self.r_receivedKeys) {
        NSString *uname = [keyDic objectForKey:@"uname"];
        for (NSString *lockUname in self.r_keysNamesArr) {
            if([lockUname isEqualToString:uname]){
                [self.r_keysNamesArr removeObject:lockUname];
                break;
            }
        }
        [self.r_keysNamesArr addObject:uname];
    }
    NSLog(@"所有的锁名：%@",self.r_keysNamesArr);
    if(self.r_keysNamesArr.count == 0){
        [KLHelp setNoDateImageWithView:self.view type:0];
    }
    
    //对收到的钥匙分类
    NSMutableArray *allGroupArr = [NSMutableArray array];
    for (int i = 0; i < self.r_keysNamesArr.count; i++) {
        NSMutableArray *sigleGroupArr = [NSMutableArray array];
        for (NSDictionary *keyDic in self.r_receivedKeys) {
            if([[keyDic objectForKey:@"uname"] isEqualToString:self.r_keysNamesArr[i]]){
                [sigleGroupArr addObject:keyDic];
            }
        }
        [allGroupArr addObject:sigleGroupArr];
    }
    NSLog(@"allGroupArr:%@",allGroupArr);
    self.r_keysOrderOKArr = [allGroupArr copy];
}

#pragma mark - 初始化导航栏
-(void)naveSet{
    self.navigationController.navigationBarHidden = NO;
    self.title = @"收到的钥匙";
    self.tableView.tableFooterView = [[UIView alloc]init];
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 编辑钥匙别名
-(void)r_eidtKeyName:(UIButton *)sender{
    NSIndexPath *indexPath = (NSIndexPath *)objc_getAssociatedObject(sender, &AssociatedKeyButton3);
    self.r_clickKeyDic = self.r_keysOrderOKArr[indexPath.section][indexPath.row];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"钥匙别名编辑" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    alert.delegate = self;
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert show];
}

#pragma mark -alertView的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //修改子钥匙别名
    UITextField *tf=[alertView textFieldAtIndex:0];
    NSString *tf_text = tf.text;
    if(buttonIndex == 1 && ![HemaFunction xfunc_check_strEmpty:tf_text]){
        if([[self.r_clickKeyDic objectForKey:@"parentflag"] isEqualToString:@"2"]){
            [KLHttpAPI reviseChildKeyNameWithKeyID:[self.r_clickKeyDic objectForKey:@"id"] alias:tf_text completionHandler:^(NSDictionary *responseDic) {
                NSString *isSuccess = [responseDic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [self refreshReceiveKeyList];
                }
            } errorHandler:^(NSString *error) {
            }];
        }
    }
}
@end
